/*
 * @(#)FileCreate.java		       Project:Tools
 * Date:2013-5-3
 *
 * Copyright (c) 2013 CFuture09, Institute of Software, 
 * Guangdong Ocean University, Zhanjiang, GuangDong, China.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sinaapp.msdxblog.tools.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.io.IOUtils;

/**
 * @Author Geek_Soledad (msdx.android@qq.com)
 */
public class FileCreate {

	public static void main(String[] args) throws IOException {
		download("http://www.itzhai.com/android-download-the-file-to-the-sd-card.html", new File("E:\\test\\a.html"), true);
	}
	
	public static void download(String url, File savePath, boolean overwrite) throws IOException {
		if (savePath == null) {
			throw new IllegalArgumentException("the second parameter couldn't be null");
		}
		if (savePath.exists() && (!overwrite || savePath.isDirectory())) {
			throw new IOException("the file specified is exist or cannot be overwrite");
		}
		savePath.getParentFile().mkdirs();

		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
		InputStream input = connection.getInputStream();
		FileOutputStream output = new FileOutputStream(savePath);
		byte[] buffer = new byte[1024 * 400];
		int readSize = 0;
		while ((readSize = input.read(buffer)) != -1) {
			output.write(buffer, 0, readSize);
		}
		output.flush();
		IOUtils.closeQuietly(input);
		IOUtils.closeQuietly(output);
		connection.disconnect();
	}
}
